<template>
    <div>
        <a-card title="订单详情" :bordered="false">
            <template #extra>
              <a-space>
                <a-button v-if="allowOperation.editPrice" type="outline" @click="modifyPrice">调整价格</a-button>
                <a-button v-if="allowOperation.editConsignee" @click="editAddress" type="outline" >修改收货地址</a-button>
                <a-button v-if="allowOperation.cancel" @click="orderCancel" type="outline" >订单取消</a-button>
                <a-button v-if="orderInfo.order.orderStatus === 'UNPAID'" @click="confirmPrice" type="primary" >收款</a-button>
                <a-button  v-print="printInfoObj"  type="outline"  >打印发货单</a-button>
                <a-button @click="back()">返回</a-button>
            </a-space>
            </template>
            <a-steps :current="current" line-less  style="padding: 30px 200px 0 200px;" v-if="orderInfo.order.orderStatus !== 'CANCELLED'">
              <a-step>买家下单</a-step>
              <a-step>付款成功</a-step>
              <a-step>
                <span v-if="orderInfo.order.orderType == 'VIRTUAL'">待使用</span>
                <span v-if="orderInfo.order.deliveryMethod == 'SELF_PICK_UP'">待自提</span>
                <span v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod === 'LOGISTICS'">商家发货</span>
              </a-step>
              <a-step v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod === 'LOGISTICS'">用户收货</a-step>
              <a-step>交易完成</a-step>
            </a-steps>
          <a-steps :current="4" line-less style="padding: 30px 200px 0 200px" v-if="orderInfo.order.orderStatus === 'CANCELLED'">
            <a-step>提交申请</a-step>
            <a-step>取消处理</a-step>
            <a-step>审核通过</a-step>
            <a-step>完成</a-step>
          </a-steps>
        </a-card>
        <a-card title="订单信息" :bordered="false" style="margin-bottom: 0;padding-bottom: 0;">
          <a-row class="grid-demo">
            <a-col :span="8">
              <div>订单编号：<span>{{orderInfo.order.sn}}</span></div>
            </a-col>
            <a-col :span="8">
              <div>支付方式：<span>{{orderInfo.paymentMethodValue}}</span></div>
            </a-col>
            <a-col :span="8">
              <div>下单时间：<span>{{orderInfo.order.createTime}}</span></div>
            </a-col>
          </a-row>
          <a-row class="grid-demo">
            <a-col :span="8">
              <div>订单来源：<span>{{orderInfo.order.clientType}}</span></div>
            </a-col>
            <a-col :span="8">
              <div>付款状态：<span>{{orderInfo.payStatusValue}}</span></div>
            </a-col>
            <a-col :span="8" v-if="orderInfo.order.orderType !== 'VIRTUAL'">
              <div>配送方式：<span>{{orderInfo.deliveryMethodValue}}</span></div>
            </a-col>
          </a-row>
          <a-row class="grid-demo">
            <a-col :span="8">
              <div>订单状态：<span>{{orderInfo.orderStatusValue}}</span></div>
            </a-col>
            <a-col :span="8">
              <div>支付单号：<span>{{ orderInfo.order.tradeSn}}</span></div>
            </a-col>
            
          </a-row>
          <a-row class="grid-demo" v-if="(orderInfo.order.deliveryMethod == 'SELF_PICK_UP')">
            <a-col :span="24">自提信息：<span>{{ orderInfo.order.storeAddressPath  }}{{ orderInfo.order.storeAddressMobile }}</span></a-col>
          </a-row>
        </a-card>
        <a-card title="收货信息" :bordered="false" style="margin:0;padding-bottom: 0;padding-top: 0px;" v-if="(orderInfo.order.deliveryMethod != 'SELF_PICK_UP' &&orderInfo.order.orderType != 'VIRTUAL')">
          <a-row class="grid-demo">
            <a-col :span="8">
              <div>收货人：<span>{{orderInfo.order.consigneeName}}</span></div>
            </a-col>
            <a-col :span="8">
              <div>联系方式：<span>{{orderInfo.order.consigneeMobile}}</span></div>
            </a-col>
          </a-row>
          <a-row class="grid-demo">
            <a-col :span="8">
              <div>收货地址：<span>{{orderInfo.order.consigneeAddressPath}}{{orderInfo.order.consigneeDetail}}</span></div>
            </a-col>
            <a-col :span="8">
              <div>用户留言<span>{{orderInfo.order.remark}}</span></div>
            </a-col>
          </a-row>
        </a-card>
        <a-card title="订单日志" :bordered="false">
          <PickTablePage ref="tablePageRef" :columns="columnSorderLogTable" :dataList="orderInfo.orderLogs"
            :enablePagination="false" :bordered="true">
            <template #messageSlot="{ record }">
              <div style="text-wrap: wrap;">
                {{record}}
              </div>
            </template>
          </PickTablePage>
        </a-card>
        <a-card title="订单货物" :bordered="false">
          <PickTablePage ref="tablePageRef" :columns="columnGoodsTable"  :enablePagination="false" :bordered="true" :dataList='data'>
            <template #discounts="{ data }">
              <div v-if="data.priceDetailDTO && data.priceDetailDTO.discountPriceDetail">
                <div v-for="discount in data.priceDetailDTO.discountPriceDetail">
                  <a-tag mb-2>{{ discount.promotionName }}</a-tag>
                </div>
              </div>
              <div v-else>暂未参加任何促销活动</div>
            </template>
          </PickTablePage>
        </a-card>
        <div class="footer">
          <div class="footer-font">应付：<span class="">{{ unitPrice(orderInfo.order.priceDetailDTO.flowPrice, '¥')}}</span></div>
          <div>优惠：<span>{{ unitPrice(orderInfo.order.priceDetailDTO.discountPrice, '¥')}}</span></div>
          <div>运费：<span>{{ unitPrice(orderInfo.order.freightPrice, '￥') }}</span></div>
          <div>优惠券：<span>-{{
              unitPrice(orderInfo.order.priceDetailDTO.couponPrice, '¥')
            }}</span></div>
          <div>商品总价:<span>{{ unitPrice(orderInfo.order.priceDetailDTO.goodsPrice, '￥') }}</span></div>
        </div>  
              <!-- 订单取消 -->
      <a-modal v-model:visible="orderCancelModal" width="500px" title="取消原因">
        <a-form ref="formRef" :model="orderCancelForm" :style="{ width: '460px' }" layout="horizontal"
          auto-label-width>
          <a-form-item field="reason" label="取消原因" :rules="[REQUIRED]">
            <a-textarea placeholder="请输入取消原因" allow-clear v-model="orderCancelForm.reason" />
          </a-form-item>
        </a-form>
        <template #footer>
          <div style="text-align: right">
            <a-button @click="orderCancelModal = false">取消</a-button>
            <a-button class="marginL10" type="primary" @click="orderCancelSubmit">确认</a-button>
          </div>
        </template>
      </a-modal>
      <!-- 调整价格 -->
      <a-modal v-model:visible="adjustmentPrice" width="500px" title="修改金额">
        <div>
          <a-form :model="modifyPriceForm" :style="{ width: '460px' }" layout="horizontal"
            auto-label-width>
            <a-form-item field="reason" label="订单金额">
              <a-input-number v-model="modifyPriceForm.price" :style="{ width: '320px' }" class="input-demo" :min="0"
                :max="999999" />
              <span class="ml_10">元</span>
            </a-form-item>
          </a-form>
        </div>
        <template #footer>
          <div style="text-align: right">
            <a-button @click="adjustmentPrice = false">关闭</a-button>
            <a-button class="marginL10" type="primary"  @click="modifyPriceSubmit">调整</a-button>
          </div>
        </template>
      </a-modal>

      <!-- 修改发货地址 -->
      <a-modal v-model:visible="editAddressModal" width="630px" title="修改收件信息">
        <div>
          <a-form ref="formRef" :model="addressForm" :style="{ width: '460px' }" layout="horizontal" auto-label-width>
            <a-form-item field="consigneeName" label="收件人" :rules="[REQUIRED, VARCHAR20]">
              <a-input v-model="addressForm.consigneeName" />
            </a-form-item>
            <a-form-item field="consigneeMobile" label="联系方式" :rules="[REQUIRED, VARCHAR20]">
              <a-input v-model="addressForm.consigneeMobile" />
            </a-form-item>
            <a-form-item field="consigneeAddressPath" label="地址信息" :rules="[REQUIRED]">
              <a-input disabled v-model="addressForm.consigneeAddressPath" v-if="showRegion" />
              <a-button type="primary"  @click="regionClick" v-if="showRegion"><icon-edit />修改</a-button>
              <PickChoiceCity :api="getChildRegion" v-if="showCity" :key="isShowCity" ref="" @callback="cityRes" :ids="addressInformation" :address="addressForm.consigneeAddressPath" />
            </a-form-item>
            <a-form-item field="consigneeDetail" label="详细地址" :rules="[REQUIRED]">
              <a-input v-model="addressForm.consigneeDetail" />
            </a-form-item>
          </a-form>
        </div>
        <template #footer>
          <div style="text-align: right">
            <a-button @click="handleCancel">取消</a-button>
            <a-button class="marginL10" type="primary"  @click="handleOk">修改</a-button>
          </div>
        </template>
      </a-modal>
       <!-- 打印发货单 -->
       <a-modal v-model:visible="printModal" width="500px">
        <!-- <template #title>
          <div style="display: flex; width: 100%;">
            <div style=" width: 65%;">打印发货单</div>
          </div>
        </template> -->
        <div style="max-height:500px;overflow-y:auto;overflow-x:hidden;padding: 10px;">
          <div id="printInfo">
            <a-row>
              <a-image width="100" src="https://cdn.pickmall.cn/cdn/logo/logo2.png"></a-image>
            </a-row>
            <a-row style="font-size: 20px;margin: 5px 0;font-weight: 600;">
              订单{{ orderInfo.order.sn }}<a-tag style="margin-left: 10px;">{{ orderInfo.orderStatusValue }}</a-tag>
            </a-row>
            <a-row style="margin-top: 20px;">创建时间 ：{{ orderInfo.order.createTime }}</a-row>
            <div class="print-good-title">商品信息：</div>
            <a-table :columns="printGoodsColumns" :data="orderInfo.orderItems" :pagination="false"></a-table>
            <div class="print-good-title">订单信息：</div>
            <a-row>
            <a-table :columns="printOrderColumns" :data="orderInfo.orderItems" :pagination="false">
              <template #consigneeAddressPath="{  }">
                  <p>
                    {{ orderInfo.order.consigneeName }}
                    {{ orderInfo.order.consigneeMobile }}
                    {{ orderInfo.order.consigneeAddressPath }}
                    {{ orderInfo.order.consigneeDetail }}
                  </p>
              </template>
              <template #deliveryMethodValue="{  }">
                <p>{{ orderInfo.deliveryMethodValue }}</p>
              </template>
              <template #paymentMethodValue="{  }">
                <p>{{ orderInfo.paymentMethodValue }}</p>
              </template>
            </a-table>
            </a-row>
            <div class="printFooter" >
              <p><a-image width="100" src="https://cdn.pickmall.cn/cdn/logo/logo2.png" style="margin-left: 45%;"></a-image></p>
              <p>北京宏业汇成科技有限公司</p>
              <p>备案号：京ICP备20009696号-1</p>
            </div>
          </div>
        </div>
        <!-- <template #footer>
          <div style="text-align: right">
            <a-button @click="printModal = false">取消</a-button>
            <a-button style="margin-left: 10px;" type="primary" status="danger" v-print="printInfoObj">打印发货单</a-button>
          </div>
        </template> -->
      </a-modal>
    </div>    
  </template>
<script lang="ts" setup>
import { editOrderConsignee, orderDetail, orderPay, ordersCancel, tradeDetail, updateOrderPrice } from '@/api/order';
import { PickTablePage, PickChoiceCity } from '@pickmall/ui-v3-components'
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { ColumnsDataRule, MethodsRule } from '@/types/global';
import { unitPrice } from '@/utils/filters';
import { REQUIRED, VARCHAR20 } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from 'vue-router';
import { addressFormRule, modifyPriceFormRule, orderCancelFormRule } from './type';
import { getChildRegion } from '@/api/common';
const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>();// 表单
const isShowCity = ref(1);
const orderInfo = ref({
  order: { priceDetailDTO: {}, },
}) as any
const data = ref([]) // 表单数据
const tradeSn = ref("") // 交易编号
const showRegion = ref<boolean>(true)
const showCity = ref<boolean>(false) // 地址是否显示
const addressInformation = ref<string>()
const orderCancelModal = ref<boolean>(false) // 订单取消
const adjustmentPrice = ref<boolean>(false) // 调整价格弹框是否开启
const editAddressModal = ref<boolean>(false) // 修改收货地址
const printModal = ref<boolean>(false) // 打印发货单弹框是否开启
const allowOperation = ref({}) as any // 订单可才做选项
const modal = useCurrentInstance().globalProperties?.$modal;//  获取modal
// 订单取消
const orderCancelForm = ref<orderCancelFormRule>({
  reason: ''
})
const current = ref(1)
const orderStatusValue = ref('') // 订单状态
// 调整价格
const modifyPriceForm = ref<modifyPriceFormRule>({
  price: 0
})
// 修改收货地址
const addressForm = reactive<addressFormRule>({
  consigneeName: '',
  consigneeMobile: '',
  consigneeDetail: '',
  consigneeAddressPath: ''
});
// 打印
const printInfoObj = reactive({
  id: "printInfo",// 要打印的id名 无#号
  popTitle: '&nbsp;',// 页眉标题 默认浏览器标题 空字符串时显示undefined 使用html语言
  extraHead: '',// 头部文字 默认空
})
// 订单日志表头
const columnSorderLogTable: ColumnsDataRule[] = [
  {
    title: '操作者',
    dataIndex: 'operatorName',
  },
  {
    title: '操作类型',
    dataIndex: 'operatorType',
  }, {
    title: '时间',
    dataIndex: 'createTime',
  }, {
    title: '日志',
    dataIndex: 'message',
    width:600,
    slot: true,
    slotTemplate: 'messageSlot'
  },
]
// 物流表头
const columnLogisticsTable: ColumnsDataRule[] = [
  {
    title: '产品',
    dataIndex: 'operatorName',
  },
  {
    title: '物流公司',
    dataIndex: 'operatorName',
  },
  {
    title: '物流单号',
    dataIndex: 'operatorName',
  },
]
// 售后表头
const columnAfterSaleTable: ColumnsDataRule[] = [
  {
    title: '产品',
    dataIndex: 'operatorName',
  },
  {
    title: '售后类型',
    dataIndex: 'operatorName',
  },
  {
    title: '售后单号',
    dataIndex: 'operatorName',
  },
  {
    title: '状态',
    dataIndex: 'operatorName',
  },
  {
    title: '申请时间',
    dataIndex: 'operatorName',
  },
]
// 订单货物表头
const columnGoodsTable: ColumnsDataRule[] = [
{
    title: '产品',
    dataIndex: 'goodsName',
    slot: true,
    width: 300,
    ellipsis: false,
    slotData: {
      goods: {
        goodsImage: 'image',
        goodsName: 'goodsName',
      },
    },
  },
  {
    title: '单价',
    dataIndex: 'goodsPrice',
    currency: true,
  },
  {
    title: '数量',
    dataIndex: 'num',
  },
  {
    title: '商品总价',
    dataIndex: 'subTotal',
    currency: true,
  },
  {
    title: '参与的优惠活动',
    dataIndex: 'promotionType',
    slot: true,
    slotTemplate:'discounts'
  },
]
const sortLogisticsMethods: MethodsRule = {
    title: '操作',
    width: 100,
    methods: [
      {
        title: '查看',
        callback: 'detail',
      },
    ],
  };
const sortAfterSaleMethods: MethodsRule = {
    title: '操作',
    width: 100,
    methods: [
      {
        title: '查看',
        callback: 'detail',
      },
    ],
  };

  const printGoodsColumns = ref([
  {
    title: '产品名称',
    dataIndex: 'goodsName',
    width:500
  },
  {
    title: '货号',
    dataIndex: 'skuSn',
    width:200
  },
  {
    title: '发货数量',
    dataIndex: 'num',
    width:200
  }
])
const printOrderColumns = ref([
{
    title: '送货地址',
    dataIndex: 'consigneeAddressPath',
    width:500,
    slotName: 'consigneeAddressPath',
  },
  {
    title: '配送方式',
    dataIndex: 'deliveryMethodValue',
    slotName: 'deliveryMethodValue',
    width:200
  },
  {
    title: '支付方式',
    dataIndex: 'paymentMethodValue',
    slotName: 'paymentMethodValue',
    width:200
  }
])

// 初始化
const init = () => {
  orderDetail(route.query.id).then((res) => {
    allowOperation.value = res.data.result.allowOperationVO
    orderInfo.value = res.data.result
    data.value = res.data.result.orderItems
    orderStatusValue.value = orderInfo.value.orderStatusValue
    // diaLogKey.value = true
    if(orderStatusValue.value){
      if (orderStatusValue.value == '未付款') {
        current.value = 1;
      } else if (orderStatusValue.value == '已付款') {
        current.value = 2;
      }else if (orderStatusValue.value == '待发货' || orderStatusValue.value == '部分发货' || orderStatusValue.value == '待使用') {
        current.value = 3;
      } else if (orderStatusValue.value === '待收货') {
        current.value = 4;
      }else if (orderStatusValue.value == '已完成') {
        if (orderInfo.value.order.orderType === 'NORMAL' && orderInfo.value.order.deliveryMethod === 'LOGISTICS') {
          current.value = 5;
        } else {
          current.value = 4;
        }
      }


    }
  })
}
// 调整价格
const modifyPrice = () => {
  if (!orderInfo.value.order.flowPrice) return
  modifyPriceForm.value.price = orderInfo.value.order.flowPrice
  adjustmentPrice.value = true
}
// 调整价格确定按钮
const modifyPriceSubmit = async () => {
  const res = await updateOrderPrice(route.query.id,  modifyPriceForm.value)
  if (res.data.code == 200) {
    Message.success('修改订单金额成功');
    adjustmentPrice.value = false
    init()
  }
}
// 修改收货地址
const editAddress = () => {
  editAddressModal.value = true
  console.log(orderInfo.value.order,'orderInfo.value.order')
  if (orderInfo.value.order) {
    const { consigneeMobile, consigneeDetail, consigneeName, consigneeAddressPath, consigneeAddressIdPath } = orderInfo.value.order
    addressForm.consigneeMobile = consigneeMobile
    addressForm.consigneeDetail = consigneeDetail
    addressForm.consigneeName = consigneeName
    addressForm.consigneeAddressPath = consigneeAddressPath
    addressInformation.value = consigneeAddressIdPath
  }
}
// 修改收件信息（修改按钮）
const regionClick = () => {
  isShowCity.value += 1;
  showRegion.value = false
  showCity.value = true
}
// 级联子组件传过来的值
const cityRes = (val: any) => {
  addressInformation.value = val.ids.join(',')
  addressForm.consigneeAddressPath = val.cities.join(',')
}
// 修改发货地址确定按钮
const handleOk = async () => {
  const auth = await formRef.value?.validate();
  if (!auth) {
    const params = {
      ...addressForm,
      consigneeAddressIdPath: addressInformation.value
    }
    editOrderConsignee(route.query.id, params).then((res: any) => {
      console.log(res);
      if (res.data.code == 200) {
        Message.success('修改成功！');
        editAddressModal.value = false // 关闭弹框
        showRegion.value = true
        showCity.value = false
        init()
      }
    })
  }
}
const handleCancel = () => {
  editAddressModal.value = false // 关闭弹框
  showRegion.value = true
  showCity.value = false
}
// 订单取消
const orderCancel = () => {
  orderCancelModal.value = true
}
// 订单取消弹框确认
const orderCancelSubmit = async () => {
  const auth = await formRef.value?.validate();
  if (!auth) {
    const res = await ordersCancel(route.query.id, orderCancelForm.value)
    if (res.data.code == 200) {
      Message.success('取消成功！');
      init()
      orderCancelModal.value = false
      location.reload();
    }
  }
}
// 收款
const confirmPrice = () => {
  modal.confirm({
    title: '提示',
    content:
      "您确定要收款吗？线下收款涉及库存变更，需异步进行，等待约一分钟刷新列表查看",
    alignCenter: false,
    onOk: async () => {
      const res = await orderPay(tradeSn.value)
      if (res.data.code == 200) {
        Message.success('收款成功');
        init()
      }
    }
  });
}
  // 返回
  const back = () => {
    router.push({ name: 'order-list' })
  }
// 初始化
onMounted(() => {
  init()
  tradeDetail(route.query.id).then((res)=>{
    tradeSn.value = res.data.result.trade.sn
    console.log('tradeSn.value', tradeSn.value)
  })
})
</script>
<style  lang="less" scoped>
 :deep(.arco-card-header){
    border-bottom: none!important;
    }
.arco-card{
    margin: 20px 0;
    padding: 20px;
}
.grid-demo{
  margin:0  0 15px 40px;
  span{
    color: #000;
  }
}
.footer{
  padding: 20px;
    height: 150px;
    width: 100%;
    display: flex;
    flex-direction: row-reverse;
    div{
      margin-left: 15px;
      color: #999;
    }
    .footer-font{
      font-size: 16px;
      color: #000;
     margin-top: -2px;
      span{
        color: #165DFF;
      }
    }
}
.printgoodtitle {
  font-size: 14px;
  line-height: 1.5;
  margin-top: 15px;
  color: #333;
}

.printgoodinfo {
  // font-size: 14px;
  // background: #f2f2f2;
  // border-bottom:2px solid #333 ;
  padding: 10px;
  overflow: hidden;
  color: #333;

  .printgooditem {
    border-bottom: 1px solid #e8eaec;
    display: flex;
    align-items: flex-start;
    overflow: hidden;
    line-height: 30px;
    margin-bottom: 10px;
    padding-bottom: 10px;

    .printgoodname {
      flex: 1;
      overflow: hidden;

      .printgoodguid {
        font-size: 12px;
        color: #999999;
        line-height: 1.5;

        .printgoodguiditem {
          margin-right: 10px;
        }
      }
    }

    .printgoodprice {
      width: 135px;
      margin-left: 15px;
    }

    .printgoodnumber {
      width: 85px;
      margin-left: 15px;
    }
  }
}
.print-good-title {
  font-size: 14px;
  line-height: 1.5;
  margin-top: 15px;
  margin-bottom: 15px;
  color: #000;
}
.printFooter{
    position: absolute;
    // position: fixed
    bottom: 0px;
    /* height: 400px; */
    // left: 50%;
    width: 100%;
    p{      
      text-align: center;
    }
}



</style>
